<template>
  <div class="procure-inventory-allot">
    <!-- 搜索表单 -->
    <div class="search-wrap mt20">
      <SearchForm
        ref="searchFormRef"
        :list="[...formList]"
        colBtn
        @submit="search"
        @reset="reset"
        @daterangeChange="daterangeChange"
      ></SearchForm>
    </div>

    <!-- 今日/昨日/近7日/近30日等，创建订单按钮，关键词搜索 -->
    <div class="center-search-wrap">
      <div>
        <div class="left">
          <el-button type="primary" @click="$router.push({ path: '/procure/inventory-allot/add', query: {} })">
            创建库存调拨
          </el-button>
          <!-- <div class="date-filter">
            <el-radio-group v-model="postData.date" @change="changeDate">
              <el-radio-button label="今天" :value="0" />
              <el-radio-button label="昨天" :value="1" />
              <el-radio-button label="近7天" :value="7" />
              <el-radio-button label="近30天" :value="30" />
            </el-radio-group>
          </div> -->
        </div>
        <div class="right">
          <!-- <el-button class="ml20" type="primary" @click="$router.push({ path: '/procure/outbound/add', query: {} })">
            创建库存调拨
          </el-button> -->
        </div>
      </div>
    </div>

    <!-- 表单数据 -->
    <el-table class="jzt-table" :data="list" stripe style="width: 100%">
      <el-table-column prop="allotNo" show-overflow-tooltip label="调拨编码" width="180" />
      <el-table-column prop="calloutWarehouseName" show-overflow-tooltip label="调出仓库" width="100">
        <template #default="scope">
          <span>{{ scope.row.calloutWarehouseName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="intoWarehouseName" show-overflow-tooltip label="调入仓库" width="100">
        <template #default="scope">
          <span>{{ scope.row.intoWarehouseName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="allotQuantity" show-overflow-tooltip label="调拨数量" />
      <el-table-column prop="allotPartQuantity" show-overflow-tooltip label="调拨件数" />
      <el-table-column prop="allotAmount" show-overflow-tooltip label="调拨费用" width="100">
        <template #default="scope">
          <span style="color: #ff3333">¥{{ scope.row.allotAmount || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="allotStatus" label="调拨状态" width="120">
        <template #default="scope">
          <!-- <el-tag v-show="scope.row.allotStatus === 1" type="warning"> 待出库 </el-tag>
          <el-tag v-show="scope.row.allotStatus === 2" type="primary"> 已出库,待入库 </el-tag>
          <el-tag v-show="scope.row.allotStatus === 3" type="primary">部分入库 </el-tag>
          <el-tag v-show="scope.row.allotStatus === 4" type="success">已完成 </el-tag>
          <el-tag v-show="scope.row.allotStatus === 5" type="info">已撤销 </el-tag> -->
          <el-tag
            :type="
              scope.row.allotStatus === 1
                ? 'warning'
                : scope.row.allotStatus === 2 || scope.row.allotStatus === 3
                  ? 'primary'
                  : scope.row.allotStatus === 4
                    ? 'success'
                    : 'info'
            "
            >{{ getEnumName("inventory_allot_status", scope.row.allotStatus) }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="customerName" show-overflow-tooltip label="借调客户" width="180">
        <template #default="scope">
          <span>{{ scope.row.secondmentCustomer || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" show-overflow-tooltip label="创建日期" width="180" />
      <el-table-column prop="createBy" show-overflow-tooltip label="创建人" width="180" />
      <el-table-column prop="outboundTime" show-overflow-tooltip label="出库时间" width="180">
        <template #default="scope">
          <span>{{ scope.row.outboundTime || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inboundTime" show-overflow-tooltip label="入库时间" width="180">
        <template #default="scope">
          <span>{{ scope.row.inboundTime || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="224">
        <template #default="scope">
          <RemarkEditor v-model="scope.row.remark" :isEdit="false" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="action" label="操作" width="170">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="
              toPath({
                path: '/procure/inventory-allot/detail',
                query: { allotId: scope.row.allotId, allotStatus: scope.row.allotStatus }
              })
            "
          >
            详情
          </el-button>
          <el-button
            v-show="scope.row.allotStatus === 1"
            link
            type="primary"
            size="small"
            @click="
              () => {
                currObj = scope.row;
                _isOpenCancel = true;
              }
            "
          >
            撤销调拨
          </el-button>
          <el-button
            v-show="scope.row.allotStatus === 5"
            link
            type="danger"
            size="small"
            @click="
              () => {
                currObj = scope.row;
                _isOpenDel = true;
              }
            "
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pt20 pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 确认撤销调拨 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenCancel"
      :message="'您正在操作撤销调拨单，当前操作不可逆，是否继续执行撤销调拨申请？'"
      :submitBtnText="'确认撤销调拨'"
      @submit="returnSubmitCancel"
    />
    <!-- 确认删除 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenDel"
      :message="'删除后，当前数据将被永久删除，请谨慎操作，是否继续删除？'"
      :submitBtnText="'确认'"
      @submit="returnSubmitDel"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import moment from "moment";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import useCodeArrStore from "@/store/modules/select";
const store = useCodeArrStore();
import { ElMessage } from "element-plus";
import { getAllotList, revoke, allotDel } from "@/apis/procure/inventory-allot";
import RemarkEditor from "@/components/RemarkEditor";
import { useRouter } from "vue-router";
const router = useRouter();

const searchFormRef = ref();
const formList = ref([
  {
    label: "调拨状态",
    model: "allotStatus",
    type: "select",
    labelWidth: "70",
    data: [],
    props: { label: "dictLabel", value: "dictValue" }
  },
  {
    label: "出库时间",
    model: "outTime",
    type: "daterange",
    labelWidth: "70"
  },
  {
    label: "入库时间",
    model: "entryTime",
    type: "daterange",
    labelWidth: "70"
  },
  {
    label: "是否借调客户",
    model: "secondmentCustomer",
    type: "select",
    labelWidth: "70",
    data: [
      {
        value: 1,
        label: "是"
      },
      {
        value: 0,
        label: "否"
      }
    ]
  },
  {
    label: "借调客户搜索",
    model: "secondmentCustomerKeyword",
    type: "input",
    placeholder: "请输入借调客户姓名或电话号码搜索",
    labelWidth: "70"
  }
]);
const formData = ref({});
const postData = ref({ date: null });
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const optionInfo = ref({ isShow: false });
const _isOpenDel = ref(false);
const _isOpenCancel = ref(false);
const currObj = ref({});

onMounted(async () => {
  const allotStatusList = useCodeArrStore().getDict("inventory_allot_status");
  for (let item of formList.value) {
    if (item.model === "allotStatus") {
      item.data = allotStatusList;
    }
  }

  getList();
});
watch(
  () => store.dict,
  val => {
    // console.log("数据字典获取到了", val);
    formList.value.map(item => {
      if (item.model === "allotStatus") {
        // 调拨单状态。下拉数据获取
        item.data = store.getDict("inventory_allot_status");
      }
    });
  },
  { deep: true, immediate: true }
);

const toPath = obj => {
  //打开新页签
  const routeUrl = router.resolve(obj);
  window.open(routeUrl.href, "_blank");
};

//数据字典转换
const getEnumName = (dictKey, code) => {
  return store.getDictName(dictKey, code);
};

//撤销调拨
const returnSubmitCancel = () => {
  // console.log("这里请求撤销调拨接口");
  revoke({ allotId: currObj.value.allotId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "调拨单撤销成功！",
        type: "success"
      });
      getList();
      _isOpenCancel.value = false;
    }
  });
};

//确认删除
const returnSubmitDel = () => {
  // console.log("这里请求删除接口", currObj.value.deliveryId);
  allotDel({ allotId: currObj.value.allotId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      _isOpenDel.value = false;
    }
  });
};

const changeDate = val => {
  const { start, end } = getTimeRange(val);
  formData.value.actualStockTimeStart = start;
  formData.value.actualStockTimeEnd = end;
  getList();
};

const getTimeRange = num => {
  if (num !== null) {
    let start = "";
    let end = "";
    if (num === 0) {
      start = moment().startOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
      end = moment().endOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
    } else if (num === 1) {
      start = moment().subtract(1, "day").startOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
      end = moment().subtract(1, "day").endOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
    } else {
      start = moment()
        .subtract(num - 1, "day")
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
      end = moment().format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
    }

    searchFormRef.value.setFormData("outTime", [start, end]);
    return { start, end };
  }
};

// 关闭异常数据弹窗
const close = () => {
  optionInfo.value.isShow = false;
};
//异常处理成功的回调
const errorSubmit = () => {
  optionInfo.value.isShow = false;
  getList();
};

//查询出库单列表数据
const getList = () => {
  getAllotList({
    ...formData.value,
    page: pagination.value.page,
    size: pagination.value.size,
    outboundStartTime: postData.value.date ? getTimeRange(postData.value.date).start : formData.value.outboundStartTime,
    outboundEndTime: postData.value.date ? getTimeRange(postData.value.date).end : formData.value.outboundEndTime,
    inboundStartTime: postData.value.date ? getTimeRange(postData.value.date).start : formData.value.inboundStartTime,
    inboundEndTime: postData.value.date ? getTimeRange(postData.value.date).end : formData.value.inboundEndTime
  }).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

// 表单查询组件submit回调
const search = form => {
  // console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    // 出库时间
    _form.outboundStartTime = form?.outTime ? form?.outTime[0] : null;
    _form.outboundEndTime = form?.outTime ? form?.outTime[1] : null;
    // 入库时间
    _form.inboundStartTime = form?.entryTime ? form?.entryTime[0] : null;
    _form.inboundEndTime = form?.entryTime ? form?.entryTime[1] : null;

    const fieldsToDelete = ["outTime", "entryTime"];
    fieldsToDelete.forEach(field => {
      delete _form[field];
    });
    formData.value = _form;
    // console.log("处理后的数据", formData.value);
  } else {
    formData.value = {};
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
  daterangeChange();
};

const daterangeChange = () => {
  postData.value = { date: null };
};

//清空中间的查询条件
const resetCenter = () => {
  postData.value = {};
};

const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};
</script>

<style lang="scss" scoped>
.procure-inventory-allot {
  height: calc(100% - 20px);
  overflow-y: auto;
  padding: 0 20px 20px 20px;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .center-search-wrap {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    :deep(.el-input-group__prepend) {
      padding: 0;
      box-shadow: none;
    }
    :deep(.el-input.el-input-group.el-input-group--append.el-input-group--prepend) {
      & > .el-input-group__prepend {
        border-radius: 4px 0 0 4px;
        border: 1px solid #dcdfe6;
        border-right: none;
        .el-input__wrapper {
          border-radius: 4px;
        }
        .el-cascader.el-tooltip__trigger.el-tooltip__trigger {
          border-radius: 4px 0 0 4px;
        }
      }
      & > .el-input__wrapper {
        border: 1px solid #dcdfe6;
      }
    }
    :deep(.el-input__wrapper) {
      box-shadow: none;
    }
    & > div {
      display: flex;
      justify-content: space-between;
      padding: 20px 0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
        background-color: white;
        color: #007dff;
      }
    }
  }
}
</style>
